package com.jie.base.repository;

import com.jie.component.mongo.core.AbstractMongoRepository;
import com.jie.component.mongo.wrapper.LambdaMongoQueryWrapper;
import com.jie.model.mongo.base.UserVisitCityDocument;
import com.jie.model.vo.base.CityVO;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class UserVisitCityRepository extends AbstractMongoRepository<UserVisitCityDocument> {

    private static final int MAX_VISIT_CITIES = 10;

    public UserVisitCityRepository(MongoTemplate mongoTemplate) {
        super(mongoTemplate, UserVisitCityDocument.class);
    }

    /**
     * 获取用户最近访问城市
     * @param userId 用户ID
     * @param limit 限制返回数量
     * @return 城市列表
     */
    public List<CityVO> getRecentCity(Long userId, int limit) {
        LambdaMongoQueryWrapper<UserVisitCityDocument> wrapper = new LambdaMongoQueryWrapper<>();
        wrapper.eq(UserVisitCityDocument::getUserId, userId);

        return findOne(wrapper)
                .map(doc -> doc.getVisitCities().stream()
                        .limit(Math.min(limit, MAX_VISIT_CITIES))
                        .map(this::convertToCityVO)
                        .toList())
                .orElse(List.of());
    }

    /**
     * 更新用户访问城市记录
     * @param userId 用户ID
     * @param cityId 城市ID
     * @param cityName 城市名称
     * @param cityCode 城市编码
     */
    public void updateVisitCity(Long userId, Long cityId, String cityName, String cityCode) {
        UserVisitCityDocument.VisitCity visitCity = createVisitCity(cityId, cityName, cityCode);

        // TODO: 应该是原子的操作

        // 先查询现有记录
        LambdaMongoQueryWrapper<UserVisitCityDocument> queryWrapper = new LambdaMongoQueryWrapper<>();
        queryWrapper.eq(UserVisitCityDocument::getUserId, userId);

        UserVisitCityDocument document = findOne(queryWrapper).orElseGet(() -> {
            UserVisitCityDocument newDoc = new UserVisitCityDocument();
            newDoc.setUserId(userId);
            newDoc.setVisitCities(new ArrayList<>());
            return newDoc;
        });

        // 更新访问城市列表
        List<UserVisitCityDocument.VisitCity> visitCities = document.getVisitCities();

        // 移除相同cityId的记录
        visitCities.removeIf(city -> city.getCityId().equals(cityId));

        // 添加新记录到开头
        visitCities.add(0, visitCity);

        // 限制列表大小
        if (visitCities.size() > MAX_VISIT_CITIES) {
            visitCities = visitCities.subList(0, MAX_VISIT_CITIES);
        }

        document.setVisitCities(visitCities);

        // 保存更新后的文档
        save(document);
    }

    private UserVisitCityDocument.VisitCity createVisitCity(Long cityId, String cityName, String cityCode) {
        UserVisitCityDocument.VisitCity visitCity = new UserVisitCityDocument.VisitCity();
        visitCity.setCityId(cityId);
        visitCity.setCityCode(cityCode);
        visitCity.setCityName(cityName);
        visitCity.setVisitTime(System.currentTimeMillis());
        return visitCity;
    }

    private CityVO convertToCityVO(UserVisitCityDocument.VisitCity visitCity) {
        return CityVO.builder()
                .id(visitCity.getCityId())
                .name(visitCity.getCityName())
                .code(visitCity.getCityCode())
                .build();
    }
} 